<?php

namespace app\api\controller\v2;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Channels;
use app\admin\model\cms\Comment;
use app\admin\model\cms\IntroduceModel;
use app\admin\model\cms\LiveCategoryModel;
use app\admin\model\cms\OrderModel;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\VideoCategoryModel;
use app\admin\model\CutWordIndex;
use app\admin\model\Investment;
use app\admin\model\InvestmentCategoryModel;
use app\admin\model\User;
use app\api\service\cms\AttachmentService;
use app\api\service\TengxunSignatureUtil;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\ChartParent;
use app\common\model\UserFavorite;
use app\common\model\UserLike;
use think\Config;
use think\db\Query;
use WeMeetingGateWay\WeMeetingApi\WeMeetingApi;
use WeMeetingGateWay\Credential;
use WeMeetingGateWay\Exception\WeMeetingException;

/**
 * 搜索
 */
class Search extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = ['login', 'mobilelogin', 'testfun'];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //搜索列表 搜索范围是网站全站的内容，包括帖子标题和内容，也包括评论、视频、直播、数据库等所有（在一个新列表展示出来）
    public function searchList()
    {
        $request = $this->request->param();//参数
        $page = $request['page'] ?? 1;//页码
        $limit = $request['limit'] ?? 20;//每页数量
        $keyword = $request['keyword'] ?? '';//关键词
        $time = $request['time'] ?? '';//时间筛选(格式:2023-09-13)
        $time = empty($time) ? date('Y-m-d') : $time;
        $time = $time . ' 23:59:59';
        $orderway = $request['orderway'] ?? 'desc';//排序方式:asc,desc
        $user = $this->auth->getUser();//用户信息
        $new_user = new \app\admin\model\User();
        $rule_column_id = $new_user->isChannelsPermission($user)['rule_column_id'];//当前用户拥有权限的的全部栏目表id
        $membershipExpiryRecord = new MembershipExpiryRecord();
        //查债市论坛
        $searchPlate = $this->searchPlate($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord);
        //查成长计划
        $searchVideo = $this->searchVideo($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord);
        //查直播
        $searchLive = $this->searchLive($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord);
        //查数据库(投研日志)
        $searchInvestment = $this->searchInvestment($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord);

        //查量化辅助、数据库、成长计划富文本
        $searchIntroduce = $this->searchIntroduce($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord);

        $res = [
            'plateList' => $searchPlate['plateList'],//论坛
            'videoList' => $searchVideo['videoList'],//视频
            'albumList' => $searchVideo['albumList'],//视频专辑
            'liveList' => $searchLive['liveList'],//直播
            'investmentList' => $searchInvestment['investmentList'],//数据库
            'introduceList' => $searchIntroduce['introduceList'],//富文本搜索
        ];
        $this->success('', $res);
    }

    //搜索论坛列表
    private function searchPlate($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord)
    {

        //得到当前用户可以看得论坛板块自有的栏目id
        $correlation_id = Channels::whereIn('id', $rule_column_id)
            ->where('parent_id', '3')//债市论坛
            ->where('status', '>', '0')//状态0=隐藏
            ->field('id,parent_id,correlation_id')
            ->column('correlation_id');

        //查询板块需要收费的自有板块id
        $plate_pay_category_ids = Plate::where('membership_price', '>', 0)
            ->where('status', 1)
            ->column('id');


        $data = new Platepost();

        if (!empty($keyword)) {
            //查询分词索引表
            $cut_word_index = new \app\api\service\cms\CutWordIndex();
            $a_id = $cut_word_index->getCutWordIndex($keyword, 'plate_post')['a_id'];
            if ($a_id) {
                $data = $data->whereIn('id', $a_id);
            } else {
                $res = [
                    'plateList' => [],
                    'total' => 0
                ];
                return $res;
            }
        }

        $data = $data->where('is_audit', 1)
            ->where('creat_time', '<=', $time)
            ->with(['user'])
            ->order('is_jing', 'desc')
            ->order('id', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();


        //附件列表
        $attachment_url_arr = [];
        foreach ($data['data'] as $v) {
            if ($v['file_data']) {
                $attachment_url_arr = array_merge($attachment_url_arr, explode(',', $v['file_data']));
            }
        }
        //获取附件列表
        $attachment_list = (new AttachmentService())->getList(['url' => array_unique(array_filter($attachment_url_arr))]);

        $arList = [];
        foreach ($data['data'] as $v) {
            //得到当前文章的评论
            $commentData = Comment::where('pid', 0)->where('aid', $v['id'])
                ->where('type', 'bbs')
                ->with(['user', 'children'])
                ->limit(5)->select();

            $commentList = [];
            foreach ($commentData as $ck => $cv) {
                $commentList[$ck] = $cv->toArray();
                $commentList[$ck]['createtime'] = date('Y-m-d H:i:s', $commentList[$ck]['createtime']);
                if (!$cv['user']) {
                    //获取软删除用户
                    $cv['user'] = User::getSoftDeleteUser($cv['user_id']);
                }

                $commentList[$ck]['user'] = [
                    'id' => $cv['user']['id'] ?? '',
                    'username' => $cv['user']['nickname'] ?? '',
                    'avatar' => obsurl($cv['user']['avatar'] ?? ''),
                ];
                $commentList[$ck]['is_children'] = $cv['children'] ? 1 : 0;//是否存在子集|0:否,1:是
            }
            $is_mylike = UserLike::where('table_name', 'plate_post')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();
            $is_myfavorite = UserFavorite::where('table_name', 'plate_post')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();

            if (!$v['user']) {
                //获取软删除用户
                $v['user'] = User::getSoftDeleteUser($v['user_id']);
            }

            if ($v['user']['avatar'] ?? '') {
                $v['user']['avatar'] = obsurl($v['user']['avatar']);
            }
            if ($v['file']) {
                $v['file'] = obsurl($v['file']);
            }

            $file_img = [];
            foreach (explode(',', $v['file_img']) as $path) {
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach (explode(',', $v['file_video']) as $path) {
                $file_video[] = obsurl($path);
            }
            $file_audio = [];
            foreach (explode(',', $v['file_audio']) as $path) {
                $file_audio[] = obsurl($path);
            }
            $file_data = [];
            if ($v['file_data']) {
                $v['file_data'] = explode(',', $v['file_data']);
                foreach ($v['file_data'] as $fv) {
                    foreach ($attachment_list as $av) {
                        if ($av['url'] == $fv) {
                            $file_data[] = [
                                'filename' => $av['filename'],
                                'url' => obsurl($av['url'])
                            ];
                        }
                    }
                }

            }

            $reprint_data = [];//转发的原文信息
            if ($v['reprint_id']) {
                $reprint_article = Platepost::find($v['reprint_id']);//被转发文原文

                $r_file_img = [];
                foreach (explode(',', $reprint_article['file_img']) as $path) {
                    $r_file_img[] = obsurl($path);
                }
                $r_file_video = [];
                foreach (explode(',', $reprint_article['file_video']) as $path) {
                    $r_file_video[] = obsurl($path);
                }
                $r_file_audio = [];
                foreach (explode(',', $reprint_article['file_audio']) as $path) {
                    $r_file_audio[] = obsurl($path);
                }
                $r_file_data = [];
                if ($reprint_article['file_data']) {
                    $r_attachment = Attachment::whereIn('url', $reprint_article['file_data'])->select();
                    foreach ($r_attachment as $r_av) {
                        $r_file_data[] = [
                            'filename' => '复盘-' . $r_av['filename'],
                            'url' => obsurl($r_av['url'])
                        ];
                    }
                }

                $reprint_data = [
                    'category_type' => 'plate',//查看详情用|类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                    'comment_type' => 'bbs',//发布评论用|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                    'id' => $reprint_article['id'],
                    'post_title' => $reprint_article['postname'],//标题
                    'post_content' => $reprint_article['postcontent'],//内容
                    'post_content_text' => filteredText($reprint_article['postcontent']),//内容
                    'file_img' => array_filter($r_file_img),//图片数组
                    'file_img_num' => count(array_filter($r_file_img)),//图片数组
                    'file_video' => array_filter($r_file_video),//视频数组
                    'file_audio' => array_filter($r_file_audio),//音频数组
                    'file_data' => array_filter($r_file_data),//文件数组
                ];
            }

            $content_arr = [
//                plateList
                'channel_pid' => '3',//栏目表父级分类id|0:顶级 3=债市论坛
                'table_name' => 'plate_post',//点赞收藏用|内容以前所在表,不带前缀|news:新闻,plaza_post:广场,video:视频,plate_post:论坛
                'category_type' => 'plate',//查看详情用|类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'bbs',//发布评论用|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],
                'post_title' => $v['postname'],//标题
                'post_content' => $v['postcontent'],//内容
                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'user_id' => $v['user_id'],//用户id
                'avatar' => $v['user']['avatar'] ?? '',//用户头像
                'username' => $v['user']['nickname'] ?? '',//昵称
                'thumbnail' => $v['file'],//图片链接
                'is_accessory' => ($v['accessory'] ? 1 : 0),//是否存在附件|0:否,1:是
                'is_top' => $v['top'],//是否置顶|0:否
                'is_jing' => $v['is_jing'],//是否加精|0:否
                'is_mylike' => $is_mylike ? 1 : 0,//是否喜欢|0:否
                'is_myfavorite' => $is_myfavorite ? 1 : 0,//是否收藏|0:否
                'recommended' => $v['is_jing'],//是否推荐|0:否
                'commentList' => $commentList,//顶级评论列表
                'create_time' => $v['creat_time'],//创建时间

                'post_like' => $v['post_like'],//点赞数量
                'post_favorites' => $v['post_favorites'] ?? 0,//收藏数量
                'comment_count' => $v['comment_count'],//评论数量
                'post_hits' => 0,//点击量
                'post_forward' => $v['post_forward'],//转发数量

                'is_author' => 0,//是否为作者|0:否,1:是
                'is_member_expire' => 0,//会员是否到期|0:否,1:是

                'file_img' => array_filter($file_img),//图片数组
                'file_img_num' => count(array_filter($file_img)),//图片数组
                'file_video' => array_filter($file_video),//视频数组
                'file_audio' => array_filter($file_audio),//音数数组
                'file_data' => array_filter($file_data),//文件数组
                'reprint_id' => $v['reprint_id'],//转发的原文id|值>=1=转发,值不为真=原创
                'reprint_data' => $reprint_data,//转发的原文数据
                'is_reprint' => $this->is_reprint($v['postcontent']),//判断文章内容是否是转载 1:是,0:否
            ];

            if ($user['id'] == $v['user_id']) {
                $content_arr['is_author'] = 1;
            }


            //检测用户是否有权访问内容
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'plate_post', $v['id'], $v['plateid']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //用户没买分类
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
            }


            $arList[] = $content_arr;
        }
        $res = [
            'plateList' => $arList,
            'total' => $data['total']
        ];
        return $res;

    }

    //搜索视频列表
    private function searchVideo($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord)
    {

        //得到当前用户可以看得论坛板块自有的栏目id
        $correlation_id = Channels::whereIn('id', $rule_column_id)
            ->where('parent_id', '4')//成长计划
            ->where('status', '>', '0')//状态0=隐藏
            ->field('id,parent_id,correlation_id')
            ->column('correlation_id');

        //查询板块需要收费的自有板块id
        $plate_pay_category_ids = VideoCategoryModel::where('membership_price', '>', 0)
            ->where('status', 1)
            ->column('id');

        $data = \app\admin\model\cms\Video::where('title', 'like', "%$keyword%")
            ->whereOr('description', 'like', "%$keyword%")
            ->with(['user'])
            ->where('create_time', '<=', $time)
            ->order('is_top', 'desc')
            ->order('sort', 'desc')
            ->order('id', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();

        $arList = [];
        foreach ($data['data'] as $v) {
            //得到当前文章的评论
            $commentData = Comment::where('pid', 0)->where('aid', $v['id'])
                ->where('type', 'video')
                ->with(['user', 'children'])
                ->limit(5)->select();

            $commentList = [];
            foreach ($commentData as $ck => $cv) {
                $commentList[$ck] = $cv->toArray();
                $commentList[$ck]['createtime'] = date('Y-m-d H:i:s', $commentList[$ck]['createtime']);
                if (!$cv['user']) {
                    $cv['user'] = User::getSoftDeleteUser($cv['user_id']);
                }
                $commentList[$ck]['user'] = [
                    'id' => $cv['user']['id'],
                    'username' => $cv['user']['nickname'],
                    'avatar' => $cv['user']['avatar'],
                ];
                $commentList[$ck]['is_children'] = $cv['children'] ? 1 : 0;//是否存在子集|0:否,1:是
                $commentList[$ck]['is_author'] = 0;//是否为评论作者|1:是,0:否
                if ($commentList[$ck]['user']['id'] == $user['id']) {
                    $commentList[$ck]['is_author'] = 1;//是否为评论作者|1:是,0:否
                }
            }

            $is_mylike = UserLike::where('table_name', 'video')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();
            $is_myfavorite = UserFavorite::where('table_name', 'video')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();

            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            if ($v['video_path']) {
                if (substr($v['video_path'], 0, 1) === '/') {
                    $v['video_path'] = obsurl($v['video_path']);
                }
            }

            if (!$v['user']) {
                //获取软删除用户
                $v['user'] = User::getSoftDeleteUser($v['user_id']);
            }

            if ($v['user']['avatar'] ?? '') {
                $v['user']['avatar'] = obsurl($v['user']['avatar']);
            }


            //内容数组
            $content_arr = [
                'id' => $v['id'],
                'title' => $v['title'],//标题
                'description' => $v['description'],//描述
                'image' => $v['image'],//封面图片
                'video_path' => $v['video_path'],//视频链接
                'is_top' => $v['is_top'],//是否置顶|0:否
                'type' => $v['type'],//类型：1视频2音频
                'is_mylike' => $is_mylike ? 1 : 0,//是否喜欢|0:否
                'is_myfavorite' => $is_myfavorite ? 1 : 0,//是否收藏|0:否
                'user_id' => $v['user_id'],//用户id
                'thumbnail' => $v['user']['avatar'],//头像
                'username' => $v['user']['nickname'],//昵称
                'commentList' => $commentList,//顶级评论列表
                'create_time' => $v['create_time'],//创建时间

                'post_like' => $v['count_like'] ?? 0,//点赞数量
                'post_hits' => $v['count_view'] ?? 0,//点击量
                'post_favorites' => $v['count_favorite'] ?? 0,//收藏数量
                'comment_count' => $v['count_comment'],//评论数量
                'post_forward' => $v['count_forward'] ?? 0,//转发数量

                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
            ];

            //判断栏目分类是不是在用户拥有的栏目权限表中,不在就验证用户有无购买自有栏目,也不在就验证用户有没有单独购买文章
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $v['id'], $v['video_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //用户没买分类
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
                $content_arr['description'] = '';
                $content_arr['image'] = '';
                $content_arr['video_path'] = '';
            }
            $arList[] = $content_arr;
        }

        //获取专辑
        $albumList_model = AlbumModel::where('table_name', 'video_category')
            ->where('name', 'like', "%$keyword%")
            ->whereOr('introduction', 'like', "%$keyword%")
            ->order('sort', $orderway)
            ->select();
        $album_count = count($albumList_model);
        foreach ($albumList_model as $v) {
            //内容数组
            $content_arr = [
                'id' => $v['id'],//专辑id
                'name' => $v['name'],//专辑名称
                'introduction' => $v['introduction'],//介绍
                'cover_image' => obsurl($v['cover_image']),//封面图url
                'table_name' => $v['table_name'],//分类类型|数据源不加前缀的表名|video_category=视频
                'category_id' => $v['category_id'],//所属分类id数据源不加前缀的表中的id|专辑归属的分类id
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'membership_duration' => $v['membership_duration'],//会员天数|默认0天
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
                'quantity_sold' => OrderModel::where('table_name', 'album')->where('goods_id', $v['id'])->where('pay_status', 1)->count()//专辑购买数量
            ];
            //判断栏目分类是不是在用户拥有的栏目权限表中,不在就验证用户有无购买自有栏目,也不在就验证用户有没有单独购买文章
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'album', $v['id'], $v['category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //用户没买分类
                $content_arr['is_member_expire'] = 1;
            }

            $albumList[] = $content_arr;
        }

        $res = [
            'videoList' => $arList,
            'albumList' => $albumList ?? [],
            'total' => $data['total']
        ];
        return $res;

    }

    //搜索直播列表
    private function searchLive($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord)
    {

        //得到当前用户可以看得论坛板块自有的栏目id
        $correlation_id = Channels::whereIn('id', $rule_column_id)
            ->where('parent_id', '6')//直播
            ->where('status', '>', '0')//状态0=隐藏
            ->field('id,parent_id,correlation_id')
            ->column('correlation_id');

        //查询板块需要收费的自有板块id
        $plate_pay_category_ids = LiveCategoryModel::where('membership_price', '>', 0)
            ->where('status', 1)
            ->column('id');

        $data = \app\admin\model\cms\Live::where('title', 'like', "%$keyword%")
            ->whereOr('description', 'like', "%$keyword%")
            ->where('live_time', '<=', strtotime($time))
            ->order('is_top', 'desc')
            ->order('id', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();

        $arList = [];
        foreach ($data['data'] as $v) {
            $comment_count = Comment::favTotal($v['id'], 'live');
            $channels_id = Channels::where('parent_id', 5)->where('correlation_id', $v['live_category_id'])->value('id');
            //内容数组
            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            $content_arr = [
                'channels_id' => $channels_id,
                'id' => $v['id'],
                'title' => $v['title'],//标题
                'description' => $v['description'],//描述
                'image' => $v['image'],//封面图片
                'live_url' => $v['live_url'],//直播地址
                'live_time' => $v['live_time'],//直播时间
                'is_top' => $v['is_top'],//是否置顶|0:否
                'is_start_live' => $v['is_start_live'],//是否开始直播|0:否
                'create_time' => $v['create_time'],//创建时间
                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'comment_count' => $comment_count,//评论数量
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
            ];

            //检测用户是否有权访问内容
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'live', $v['id'], $v['live_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //用户没买分类
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
                $content_arr['description'] = '';
                $content_arr['live_url'] = '';
            }

            $arList[] = $content_arr;
        }

        $res = [
            'liveList' => $arList,
            'total' => $data['total']
        ];
        return $res;

    }

    //搜索投研日志(改名为数据库)列表
    private function searchInvestment($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord)
    {

        //得到当前用户可以看得论坛板块自有的栏目id
        $channels = Channels::whereIn('id', $rule_column_id)
            ->where('parent_id', '7')//数据库
            ->where('status', '>', '0')//状态0=隐藏
            ->field('id,parent_id,correlation_id')
            ->select();

        $channels_id_arr = [];
        $correlation_id = [];//得到当前用户可以看得论坛板块自有的栏目id
        foreach ($channels as $v) {
            $channels_id_arr[] = $v['id'];
            $correlation_id[] = $v['correlation_id'];//板块自有的栏目id
        }

        //查询板块需要收费的自有板块id
        $plate_pay_category_ids = InvestmentCategoryModel::where('membership_price', '>', 0)
            ->where('status', 1)
            ->column('id');


        $data = new Investment();

        if ($keyword) {
            //查询分词索引表
            $cut_word_index = new \app\api\service\cms\CutWordIndex();
            $a_id = $cut_word_index->getCutWordIndex($keyword, 'investment')['a_id'];
            if ($a_id) {
                $data = $data->whereIn('id', $a_id);
            } else {
                $res = [
                    'investmentList' => [],
                    'total' => 0
                ];
                return $res;
            }
        }
        $data = $data->whereOr('content_time', '<=', $time)
            ->order('content_time', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();

        $arList = [];
        foreach ($data['data'] as $v) {

            //判断是否分类是只显示文件的
            $is_show_file = InvestmentCategoryModel::where('id', $v['investment_category_id'])->value('type');
            $file_list = [];
            if ($is_show_file == 1) {
                $file_list = json_decode($v['file_list'], true) ?? [];
                foreach ($file_list as &$fv) {
                    $fv['url'] = obsurl($fv['url']);
                }
            }

            //内容数组
            $content_arr = [
                'id' => $v['id'],
                'macro_content' => $v['macro_content'],//宏观面
                'policy_content' => $v['policy_content'],//政策面
                'fund_content' => $v['fund_content'],//资金面及预期
                'emotion_content' => $v['emotion_content'],//情绪面
                'expect_content' => $v['expect_content'],//市场预期/关注
                'news_content' => $v['news_content'],//市场新闻
                'content_time' => date('Y-m-d H:i:s', $v['content_time']),//时间
                'create_time' => date('Y-m-d H:i:s', $v['createtime']),//创建时间
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
                'is_show_file' => $is_show_file,//0=不展示文件,1=展示文件
                'file_list' => $file_list,
            ];

            //判断栏目分类是不是在用户拥有的栏目权限表中,不在就验证用户有无购买自有栏目,也不在就验证用户有没有单独购买文章
            if (!in_array($v['investment_category_id'], $correlation_id)) {
                //判断分类是否收费
                if (in_array($v['investment_category_id'], $plate_pay_category_ids)) {
                    //判断用户是否购买该分类
                    $isCategoryMemberExpire = $membershipExpiryRecord->isMemberExpire($user['id'], 'categories', 'investment_category', $v['investment_category_id']);
                    if ($isCategoryMemberExpire['code'] != 200) {
                        //用户没买分类
                        $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
                    }
                }
            }


            $arList[] = $content_arr;
        }
        $res = [
            'investmentList' => $arList,
            'total' => $data['total']
        ];
        return $res;
    }

    //分类富文本搜索
    private function searchIntroduce($user, $keyword, $time, $orderway, $page, $limit, $rule_column_id, $membershipExpiryRecord)
    {

        //得到当前用户可以看得论坛板块自有的栏目id
        $channels = Channels::whereIn('parent_id', [7, 4, 2])//量化辅助+成长计划+数据库
        ->where('status', '>', '0')//状态0=隐藏
        ->field('id,parent_id,correlation_id')
            ->select();

        $channels_ids = [];
        $correlation_id = [];//得到当前用户可以看得论坛板块自有的栏目id
        foreach ($channels as $v) {
            if (in_array($v['id'], $rule_column_id)) {
                $channels_ids[] = $v['id'];
            } else {
                switch ($v['parent_id']) {
                    case '2':
                        $correlation_id[2][] = $v['correlation_id'];//板块自有的栏目id
                        break;
                    case '4':
                        $correlation_id[4][] = $v['correlation_id'];//板块自有的栏目id
                        break;
                    case '7':
                        $correlation_id[7][] = $v['correlation_id'];//板块自有的栏目id
                        break;
                }
            }
        }

        //根据$correlation_id 查询对应板块中免费的分类,在通过这些免费的分类得到Channels表中的id,然后讲新得到的$channels_ids与最初开始的$channels_ids进行合并去重;

        $new_channels_id = [];
        if (!empty($correlation_id[2])) {
            $category_id = ChartParent::whereIn('id', $correlation_id[2])->where('membership_price', '<', 0.01)->column('id');
            if ($category_id) {
                $ids = Channels::where('parent_id', 2)->whereIn('correlation_id', $category_id)->where('status', '>', 0)->column('id');
                if ($ids) {
                    $new_channels_id = array_merge($new_channels_id, $ids);
                }
            }
        }
        if (!empty($correlation_id[4])) {
            $category_id = VideoCategoryModel::whereIn('id', $correlation_id[4])->where('membership_price', '<', 0.01)->where('status', 1)->column('id');
            if ($category_id) {
                $ids = Channels::where('parent_id', 4)->whereIn('correlation_id', $category_id)->where('status', '>', 0)->column('id');
                if ($ids) {
                    $new_channels_id = array_merge($new_channels_id, $ids);
                }
            }
        }
        if (!empty($correlation_id[7])) {
            $category_id = InvestmentCategoryModel::whereIn('id', $correlation_id[7])->where('membership_price', '<', 0.01)->where('status', 1)->column('id');
            if ($category_id) {
                $ids = Channels::where('parent_id', 7)->whereIn('correlation_id', $category_id)->where('status', '>', 0)->column('id');
                if ($ids) {
                    $new_channels_id = array_merge($new_channels_id, $ids);
                }
            }
        }
        $channels_ids =  array_unique(array_merge($channels_ids, $new_channels_id));

        if (!$channels_ids) {
            //无查看权限，直接返回空数组
            $res = [
                'total' => 0,
                'introduceList' => [],
            ];
            return $res;
        }

        $model = IntroduceModel::whereIn('channels_id', $channels_ids);
        if ($keyword) {
            //查询分词索引表->得到文章id
            $cut_word_index = new \app\api\service\cms\CutWordIndex();
            $a_id = $cut_word_index->getCutWordIndex($keyword, 'introduce')['a_id'];
            if ($a_id) {
                $model = $model->whereIn('id', $a_id);
            } else {
                $res = [
                    'total' => 0,
                    'introduceList' => [],
                ];
                return $res;
            }
        }

        $model = $model->with(['admin', 'channels'])
            ->order('id', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();

        $res = [
            'total' => $model['total'],
            'introduceList' => [],
        ];


        //附件列表
        $attachment_url_arr = [];
        foreach ($model['data'] as $v) {
            if ($v['file_data']) {
                $attachment_url_arr = array_merge($attachment_url_arr, explode(',', $v['file_data']));
            }
        }
        //获取附件列表
        $attachment_list = (new AttachmentService())->getList(['url' => array_unique(array_filter($attachment_url_arr))]);

        foreach ($model['data'] as $v) {

            $file_img = [];
            foreach (explode(',', $v['file_img'] ?? '') as $path) {
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach (explode(',', $v['file_video'] ?? '') as $path) {
                $file_video[] = obsurl($path);
            }
            $file_audio = [];
            foreach (explode(',', $v['file_audio'] ?? '') as $path) {
                $file_audio[] = obsurl($path);
            }
            $file_data = [];
            if ($v['file_data']) {
                $v['file_data'] = explode(',', $v['file_data']);
                foreach ($v['file_data'] as $fv) {
                    foreach ($attachment_list as $av) {
                        if ($av['url'] == $fv) {
                            $file_data[] = [
                                'filename' => $av['filename'],
                                'url' => obsurl($av['url'])
                            ];
                        }
                    }
                }

            }

            $res['introduceList'][] = [
                'id' => $v['id'],
                'content' => $v['content'],
                'file_img' => array_filter($file_img),
                'file_img_count' => count(array_filter($file_img)),
                'file_video' => array_filter($file_video),
                'file_video_count' => count(array_filter($file_video)),
                'file_audio' => array_filter($file_audio),
                'file_audio_count' => count(array_filter($file_audio)),
                'file_data' => array_filter($file_data),
                'file_data_count' => count(array_filter($file_data)),
                'admin_id' => $v['admin_id'],
                'admin' => [
                    'id' => $v['admin']['id'],
                    'nickname' => $v['admin']['nickname'],
                    'avatar' => obsurl($v['admin']['avatar']),
                ],

                'channels_id' => $v['channels_id'],
                'channels' => [
                    'id' => $v['channels']['id'],
                    'name' => $v['channels']['name'],
                    'parent_id' => $v['channels']['parent_id'],
                    'correlation_id' => $v['channels']['correlation_id'],
                ],
                'createtime' => $v['createtime'] ? date('Y-m-d H:i', $v['createtime']) : '',
            ];
        }
        return $res;
    }

    //判断文章内容是否是转载 1:是,0:否
    private function is_reprint($content)
    {
        $prefix = '【转载--';
        $is_reprint = strpos($content, $prefix) === 0;
        return $is_reprint ? 1 : 0;
    }


    public function testfun()
    {
        dd((new TengxunSignatureUtil())->updateLivePlay("12676048564959630321", "372993757", [
            "live_subject" => "复盘直播",
            "live_summary" => "复盘直播",
            "enable_live_password" => false,
            "enable_live_im" => false,
            "enable_live_replay" => false,
            "live_watermark" => [
                "watermark_opt" => 0
            ]
        ]));

    }
}
